from django.shortcuts import render
# Create your views here.


from .Ser import *
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response


#查询班级及班级下的课程
class ShowCourse(APIView):
    def get(self,request):
        cla = Sclass.objects.all()
        ser = SclassSER(cla,many=True)
        return Response({"code":201,'list':ser.data})

class ChangeClass(APIView):
    def post(self,request):
        #升班
        #获取小朋友id
        id = request.data.get('id')
        #查询小朋友现在所在班级，type=3返回，1，2
        stu = Stu.objects.filter(id=id).first()
        ser = SclassSER(stu)
        s = ser.data
        if s['cla']['type'] == 1:
            #升级为中班
            #查询类型为中班的班级id
            cla = Sclass.objects.filter(type=2).first()
            stu.cla_id = cla.id
            stu.save()
            return Response({"code":200})
        elif s['cla']['type'] == 2:
            #升级为大班
            #查询类型为中班的班级id
            cla = Sclass.objects.filter(type=3).first()
            stu.cla_id = cla.id
            stu.save()
            return Response({"code":200})
        else:
            #返回不能升级
            return Response({"code":202})

#注册
class Reg(APIView):
    def post(self, request):
        ser = StuSER(data=request.data)
        if ser.is_valid():
            ser.save()
            # 注册成功，返回stu id name
            stu = Stu.objects.filter(username=request.data.get('username')).first()
            return Response({"code": 200, 'id': stu.id, 'name': stu.name})
        else:
            print(ser.errors)
            return Response({"code": 204})
        
    def get(self, request):
        id = request.GET.get('id')
        stu = Stu.objects.filter(id=id).first()
        ser = StuSER(stu)
        return Response({"code": 205, 'cla': ser.data})
